{% extends 'base.html' %}

{% block head_title %}
this is amazing!!!!
{% endblock head_title%}


{% block content %}

<div id='tweetme-2'></div>

<div class='row text-center'>
    <div class='col'>
        <h1>Welcome to Tweetme 2</h1>
    </div>
</div>

<div class='row mb-3'>
    <div class='col-md-4 mx-auto col-10'>
        <form class='form' id='tweet-create-form' method='POST' action='/create_tweet'>
            {% csrf_token %}
            <div class="d-none alert alert-danger" id="tweet-create-form-error"></div>
            <input type='hidden' value='/' name='next' />
            <textarea class='form-control' required="required" name='content' placeholder='Your tweet...'></textarea>
            <button type='submit' class='btn btn-primary'>Tweet</button>
        </form>
    </div>
</div>



<div class='row' id='tweets'>
    Loading...
</div>

<script>
// django doc get crsf token
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = cookies[i].trim();
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

function handleTweetFormError(msg, display){
    var myErrorDIv = document.getElementById("tweet-create-form-error")
    if(display === true){
        myErrorDIv.setAttribute("class", "d-block alert alert-danger")
        myErrorDIv.innerText = msg
    } else {
        myErrorDIv.setAttribute("class", "d-none alert alert-danger")
    }
}

// 提交推特内容
function handleTweetCreateFormSubmit(event){
    event.preventDefault()
    const myForm = event.target
    const myFormData = new FormData(myForm)
    const url = myForm.getAttribute("action")
    const method = myForm.getAttribute("method")
    const xhr = new XMLHttpRequest()
    const responseType = "json"
    xhr.responseType = responseType
    xhr.open(method, url)
    xhr.setRequestHeader("HTTP_X_REQUESTED_WITH", "XMLHttpRequest")
    xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest")
    xhr.onload = function(){
        if(xhr.status === 201){
            const newTweetJson = xhr.response
            handleTweetFormError("", false)
            const newTweetElement = formatTweetElement(newTweetJson)
            const ogHtml = tweetsContainerElement.innerHTML
            tweetsContainerElement.innerHTML = newTweetElement + ogHtml
            myForm.reset()
        } else if(xhr.status === 400){
            const errorJson = xhr.response
            const contentError = errorJson.content
            let contentErrorMsg;
            if(contentError){
                contentErrorMsg = contentError[0]
                if(contentErrorMsg){
                    handleTweetFormError(contentErrorMsg, true)
                } else {
                    alert("An error ocureed")
                } 
            } else {
                    alert("An error ocureed")
            }
        } else if(xhr.status === 500){
            alert("server error")
        } else if(xhr.status === 401){
            alert("you should log in")
            window.location.href("/login")
        } else if (xhr.status === 403) {
            alert("should log in")
        }
    }
    xhr.onerror = function(){
        alert("error occurred")
    }
    xhr.send(myFormData)
}

const tweetCreateFormEl = document.getElementById("tweet-create-form")
tweetCreateFormEl.addEventListener("submit", handleTweetCreateFormSubmit)

const tweetsContainerElement = document.getElementById("tweets")

function loadTweets(tweetsElement){
    const xhr = new XMLHttpRequest()
    const method = 'GET' // "POST"
    const url = "/tweets"
    const responseType = "json"
    xhr.responseType = responseType
    xhr.open(method, url)
    xhr.onload = function() {
        const serverResponse = xhr.response
        const listedItems = serverResponse // array
        var finalTweetStr = ""
        var i;
        for (i=0;i<listedItems.length; i++) {
            var tweetObj = listedItems[i]
            var currentItem = formatTweetElement(tweetObj)
            finalTweetStr += currentItem
        }
        tweetsElement.innerHTML = finalTweetStr
    }
    xhr.send()
}

loadTweets(tweetsContainerElement)


function handleDidLike (tweet_id, currentCount, action) {
    console.log(tweet_id, currentCount)
    const url = "api/tweets/action"
    const method = "POST"
    const data = JSON.stringify({
        id: tweet_id,
        action: action
    })
    const xhr = new XMLHttpRequest()
    const csrftoken = getCookie('csrftoken')
    xhr.open(method, url)
    xhr.setRequestHeader("Content-Type", "application/json")
    xhr.setRequestHeader("HTTP_X_REQUESTED_WITH", "XMLHttpRequest")
    xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest")
    xhr.setRequestHeader("X-CSRFToken", csrftoken)
    xhr.onload = function(){
        loadTweets(tweetsContainerElement)
    }
    xhr.send(data)
    return 
}

function UnLikeBtn(tweet) {
    return "<button class='btn btn-outline-success btn-sm' onclick=handleDidLike(" + 
    tweet.id + "," + tweet.likes + ",'unlike')>UnLike</button>"
}

function RetweetBtn(tweet) {
    return "<button class='btn btn-outline-success btn-sm' onclick=handleDidLike(" + 
    tweet.id + "," + tweet.likes + ",'retweet')>Retweet</button>"
}

function LikeBtn(tweet) {
    return "<button class='btn btn-primary btn-sm' onclick=handleDidLike(" + 
    tweet.id + "," + tweet.likes + ",'like')>" + tweet.likes + " Likes</button>"
}

function formatTweetElement(tweet) {
    var formattedTweet = "<div class='col-12 col-md-10 mx-auto border rounded py-3 mb-4 tweet' id='tweet-" + tweet.id 
    + "'><p>" + tweet.content + 
        "</p><div class='btn-group'>" + LikeBtn(tweet) + UnLikeBtn(tweet) + RetweetBtn(tweet) +
        "</div></div>"
    return formattedTweet
}

</script>
{% endblock content %}